Mock Objects and the Languages That Support Them

Mark Leighton Fisher on 2006-03-31T17:30:29

Mock objects – transparently-substitutable mock-ups of objects used in testing – are a powerful mechanism for testing what can otherwise be intractable systems (think about testing code that uses external sensors or relational databases).

Perl has strong support for mock objects (witness my Test::MockDBI), but that is not true of all languages. This was brought to my attention when I tried – and failed – to find a usable mock object framework for either VB6 or the .NET family. All of the mock object frameworks that I found for VB6 and .NET are based on substituting a different class that implements the same interface as the class under test. This is Not Good.

IMHO, interfaces should be required only when two or more classes need to exhibit the same behaviors (like IO::File and IO::String do in common cases). Classes that need only one kind of behavior should not be required to have interfaces. Even .NET COM Interop let you declare the classes as AutoDual, thereby eliminating the tedium of writing a separate interface for each class as AutoDual automagically creates the necessary COM interface for you. Why should mock objects be any different?

VB6 has reached the end of its development and free-support lifecycle. The .NET family has just started its lifecycle, though. I hope that Microsoft pays heed to those developers who find that mocking-up objects is a powerful tool in testing.

P.S. Language is funny; mocking objects would be like, "Your accessors look weird," or "Constructors? *Those* are a pathetic excuse!")

P.P.S. FWIW, L# is a LISP for .NET, but in .NET 2.0 L# will require creating extraneous interfaces when mocking-up L# objects.


Amen.

jk2addict on 2006-03-31T19:12:52

I'm a .NET guy by day, perl dude by night. While .NET has nice things like NUnit, Testdriven.NET, and code coverage tools, Mocking things in .NET is a serious PITA, when it's even possible or practical.

I'm so spoiled on TDD in Perl. You can futz with the symbol table, mess with INC, and do just about anything to mock and create different scenerios.